import { api } from "@/api";
import { convertImgUrl } from "@/utils/MyFun";
import { getToken, removeToken } from "@/utils/auth";
import * as TYPE from "../action-type";

const user = {
  getUserInfo() {
    return new Promise(async (resolve, reject) => {
      try {
        const token = getToken();
        if (!token) {
          resolve({ type: "TOKEN_NOT_EXIST" });
        }
        //获取用户信息
        const res = await api.getUser();

        if (res.code === 0) {
          let {
            id,
            nickname,
            avatar,
            website,
            intro,
            email,
            ArticleLikeSet,
            CommentLikeSet,
          } = res.data;
          avatar = convertImgUrl(avatar);
          const userInfo = {
            id,
            nickname,
            avatar,
            website,
            intro,
            email,
            articleLikeSet: ArticleLikeSet.map((e) => +e), // 注意后端给的是字符串数组
            commentLikeSet: CommentLikeSet.map((e) => +e),
          };

          resolve({
            type: TYPE.USER_GETUSERINFO,
            userInfo,
          });
        } else {
          resolve({
            type: "ERROR",
          });
        }
      } catch (error) {
        resolve({
          type: "ERROR",
        });
      }
    });
  },
  articleLike(articleId) {
    return {
      type: TYPE.USER_ARTICLELKE,
      articleId: articleId,
    };
  },
  commentLike(commentId) {
    return {
      type: TYPE.USER_COMMENTLIKE,
      commentId,
    };
  },
  logout() {
    removeToken();
    return {
      type: TYPE.USER_LOGOUT,
    };
  },
};

export default user;
